<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreProductRequest;
use App\Http\Requests\UpdateProductRequest;
use App\Http\Resources\ServiceResource;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $serialNo = $request->serial_no;
        $title = $request->title;
        $per_page = $request->per_page ?? 10;

        $sort = json_decode($request->sort, true);

        $resource = Product::when($serialNo, function ($query) use ($serialNo) {
            return $query->where('serial_no', 'like', '%' . $serialNo . '%');
        })->when($title, function ($query) use ($title) {
            return $query->where('title', 'like', '%' . $title . '%');
        })->when($sort, function ($query) use ($sort) {
            foreach ($sort as $item) {
                $val = str_replace('end', '', $item['order']);
                $query->orderBy($item['field'], $val);
            }
        }, function ($query) {
            return $query->orderBy('orderby', 'desc');
        })->paginate($per_page);

        return new ServiceResource($resource);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreProductRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreProductRequest $request)
    {
        return $this->successful(Product::create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function show(Product $product)
    {
        return $this->successful($product);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateProductRequest  $request
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateProductRequest $request, Product $product)
    {
        return $this->successful($product->update($request->all()));
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Product  $product
     * @return \Illuminate\Http\Response
     */
    public function destroy(Product $product)
    {
        $product->delete();
        return $this->successful();
    }

    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->fail(400, 'ids is required');
        }
        Product::whereIn('id', $ids)->delete();
        return $this->successful($ids);
    }
}
